package com.haircut.api.login;

import cn.hutool.core.img.ImgUtil;
import cn.hutool.core.util.IdUtil;
import com.google.code.kaptcha.Producer;
import com.haircut.sys.constant.CacheConstants;
import com.haircut.sys.vo.captcha.CaptchaVo;
import com.modular.constant.BaseCodeDesc;
import com.modular.exception.ModularException;
import com.modular.result.RspMessage;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.util.FastByteArrayOutputStream;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.concurrent.TimeUnit;

/**
 * 验证码操作处理
 * 
 * @author ruoyi
 */
@RestController
@RequestMapping("/api")
public class CaptchaController
{
    private Logger logger = LoggerFactory.getLogger(CaptchaController.class);

    @Resource(name = "captchaProducer")
    private Producer captchaProducer;

    @Resource(name = "captchaProducerMath")
    private Producer captchaProducerMath;

    @Autowired
    private RedisTemplate<String,String> redisTemplate;

    /**
     * 生成验证码
     */
    @GetMapping("/captchaImage")
    public RspMessage<CaptchaVo> getCode() throws IOException
    {
        CaptchaVo captchaVo = new CaptchaVo();

        // 保存验证码信息
        String uuid = IdUtil.simpleUUID();
        String verifyKey = CacheConstants.CAPTCHA_CODE_KEY + uuid;

        String capStr = null, code = null;
        BufferedImage image = null;

        // 生成验证码
        String captchaType ="match";
        if ("match".equals(captchaType))
        {
            String capText = captchaProducerMath.createText();
            capStr = capText.substring(0, capText.lastIndexOf("@"));
            code = capText.substring(capText.lastIndexOf("@") + 1);
            image = captchaProducerMath.createImage(capStr);
        }
        else if ("char".equals(captchaType))
        {
            capStr = code = captchaProducer.createText();
            image = captchaProducer.createImage(capStr);
        }
        logger.info("uid {} code {}",uuid,code);
        redisTemplate.opsForValue().set (verifyKey, code, CacheConstants.CAPTCHA_EXPIRATION, TimeUnit.MINUTES);
        // 转换流信息写出
        FastByteArrayOutputStream os = new FastByteArrayOutputStream();
        try
        {
            ImageIO.write(image, ImgUtil.IMAGE_TYPE_JPG, os);
        }
        catch (IOException e)
        {
            throw  new ModularException(BaseCodeDesc.DEFATUL_MSG,"图片生成错误");
        }

        captchaVo.setIidd(uuid);

        captchaVo.setImage(ImgUtil.toBase64(image,ImgUtil.IMAGE_TYPE_JPG));
        return RspMessage.success(captchaVo);
    }

    public static void main(String[] args) {
        String file = "D:\\opt\\微信图片_20230120205424.jpg";
        BufferedImage image = ImgUtil.read(file);
//        System.out.println(Base64.getEncoder().encodeToString(ImgUtil.toBytes(image,ImgUtil.IMAGE_TYPE_JPG)));
        System.out.println(ImgUtil.toBase64(image,ImgUtil.IMAGE_TYPE_JPG));
    }
}
